#include "dialogcalibcams.h"
#include "ui_dialogcalibcams.h"
#include "dialogcalibrationsettings.h"


dialogCalibCams::dialogCalibCams(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::dialogCalibCams)
{
    ui->setupUi(this);
    setWindowTitle("Calibrate The Cameras");


    // Initiate the timer for updates
    tmrTimer = new QTimer(this);
    connect(tmrTimer,SIGNAL(timeout()),this,SLOT(processFrameAndUpdateGUI()));
    tmrTimer->start(20);
    playback=1;  //by default open and show the cameras when dialog first launches
}

dialogCalibCams::~dialogCalibCams()
{
    delete ui;
}



///////////////////////////////////////////////////////////////

void dialogCalibCams::processFrameAndUpdateGUI() {


    if(playback) {  // Open Cameras if needed, then Read a frame
        // Cam 0
        if (!capFile_0.isOpened()) { // open camera
            capFile_0.open(0);
            initializeCamera(capFile_0);
        }
        if (capFile_0.isOpened()) { // make sure we opened
            ui->label_Cam0_Stat->setText("Cam0: Open");  //update gui
            capFile_0.read(matVideoFile_0); //grab a frame
        } else
            ui->label_Cam0_Stat->setText("Cam0: Not Opened");

        // Cam 1
        if (!capFile_1.isOpened()) { // open file for reading video
            capFile_1.open(1);
            initializeCamera(capFile_1);
        }
        if (capFile_1.isOpened()) { // make sure we opened
            ui->label_Cam1_Stat->setText("Cam1: Open"); //update gui
            capFile_1.read(matVideoFile_1);  //grab a frame

        } else
            ui->label_Cam1_Stat->setText("Cam1: Not Opened");


        //update screen
            //cam 0
        if(capFile_0.isOpened()){
            cv::cvtColor(matVideoFile_0,matVideoFile_0,CV_BGR2RGB);
            QImage qimgVideoFile_0((uchar*)matVideoFile_0.data,matVideoFile_0.cols,
                                   matVideoFile_0.rows,matVideoFile_0.step,QImage::Format_RGB888);
            ui->label_Cam0->setScaledContents(true);
            ui->label_Cam0->setPixmap(QPixmap::fromImage(qimgVideoFile_0));

        }
            //cam 1
        if(capFile_1.isOpened()){
            cv::cvtColor(matVideoFile_1,matVideoFile_1,CV_BGR2RGB);
            QImage qimgVideoFile_1((uchar*)matVideoFile_1.data,matVideoFile_1.cols,
                                   matVideoFile_1.rows,matVideoFile_1.step,QImage::Format_RGB888);
            ui->label_Cam1->setScaledContents(true);
            ui->label_Cam1->setPixmap(QPixmap::fromImage(qimgVideoFile_1));
        }


    } else { // if video files are open, close them
        if (capFile_0.isOpened()) capFile_0.release();
        if (capFile_1.isOpened()) capFile_1.release();
    }

}


void dialogCalibCams::on_pushButton_Playback_Stop_clicked()
{
    // start playback.  change pushbutton text to "stop"
    if(!playback){
       playback=1; //set playback to true
       ui->pushButton_Playback_Stop->setText("Stop Cams");
    } else {
        playback=0; //stop playback & Update button text
        ui->pushButton_Playback_Stop->setText("Start Cams");
        ui->label_Cam0_Stat->setText("Cam0: Closed");
        ui->label_Cam1_Stat->setText("Cam1: Closed");
    }
}

// Initialize Camera Settings
void dialogCalibCams::initializeCamera(cv::VideoCapture cam){
    cam.set(CV_CAP_PROP_FRAME_WIDTH, resWidth);      //Cam Width
    cam.set(CV_CAP_PROP_FRAME_HEIGHT, resHeight);      //Cam Height
    //cam.set(CV_CAP_PROP_EXPOSURE,-2.0);
    return;
}



void dialogCalibCams::on_pushButton_CalibCam1_clicked()
{
    doit(1);

}

void dialogCalibCams::on_pushButton_CalibCam0_clicked()
{
    doit(0);
}



//calibration code template -move this to a header file eventually
int calibrate( int cameraId, int width, int height,
               int framesToGrab, int boardWidth, int boardHeight,
               float squareSize, int delay, const char* file);



void dialogCalibCams::doit(int cam)
{
    DialogCalibrationSettings dcs(this);
    if(dcs.exec() == QDialog::Accepted) {
        //do stuff

        //copy settings from dialog
        high=dcs.high;
        wide=dcs.wide;
        squareSize=dcs.squareSize;
        framesToGrab=dcs.framesToGrab;
        delayBetween=dcs.delayBetween;

        //make sure cams are closed before calling calibrate
        if (capFile_1.isOpened()) capFile_1.release();
        if (capFile_0.isOpened()) capFile_0.release();
        playback=0; //stop playback & Update button text
        ui->pushButton_Playback_Stop->setText("Start Cams");

        //form the file name for calibration
        //camX-WIDTHxHEIGTH.yml

        std::ostringstream filename;
        filename << qPrintable(projdir) << "/Cam" << cam << "_"
                 << resWidth << "x" << resHeight << ".yml";
        std::string str=filename.str();

        calibrate(cam,resWidth,resHeight,framesToGrab,wide,high,squareSize, delayBetween, str.c_str());
    }
}






